package io.renren.modules.pachong.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.modules.pachong.Movie;
import io.renren.modules.pachong.MovieTag;
import io.renren.modules.pachong.MovieTagVO;
import io.renren.modules.pachong.dao.MovieDao;
import io.renren.modules.pachong.dao.MovieTagDao;
import io.renren.modules.pachong.service.MovieService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @author Peter
 * @date 2018-8-10
 */
@Service("movieService")
public class MovieServiceImpl extends ServiceImpl<MovieDao, Movie> implements MovieService {

    public static String URL = "http://www.sihaidy.com";

    @Autowired
    private MovieTagDao movieTagDao;
    @Autowired
    private MovieDao movieDao;
    @Override
    public List<Movie> queryPage(Map<String, Object> params) {
        Page<Movie> page = new Page<>();
        page.setCurrent(Integer.valueOf((String)params.get("page")));
        page.setSize(Integer.valueOf((String)params.get("limit")));
        List<Movie> list = movieDao.getMovieList(page,params);
        return list;
    }

    @Override
    public List<MovieTagVO> selectAllMoiveTag() {
        List<MovieTagVO> resultList = new ArrayList<>();
        EntityWrapper<MovieTag> ew = new EntityWrapper<>();
        ew.gt("id",0);
        List<MovieTag> list = movieTagDao.selectList(ew);
        if (list != null && list.size() > 0) {
            int len = list.size();
            Map<Long, MovieTagVO> parentMap = new HashMap<>();
            Map<Long, List<MovieTag>> childrenMap = new HashMap<>();
            for (int i = 0; i < len; i++) {
                MovieTag m = list.get(i);
                if (m == null ) {
                    continue;
                }
                // 说明是父级标签
                if(new Long(0).equals(m.getPid())){
                    MovieTagVO v = new MovieTagVO();
                    BeanUtils.copyProperties(m,v);
                    parentMap.put(m.getId(),v);
                    continue;
                }
                if(childrenMap.containsKey(m.getPid())){
                    List<MovieTag> children = childrenMap.get(m.getPid());
                    children.add(m);
                }else{
                    List<MovieTag> children = new ArrayList<>();
                    children.add(m);
                    childrenMap.put(m.getPid(),children);
                }
            }
            Set<Map.Entry<Long, MovieTagVO>> sets = parentMap.entrySet();
            for(Map.Entry<Long, MovieTagVO> entry: sets){
                Long key = entry.getKey();
                MovieTagVO val = entry.getValue();
                val.setChildList(childrenMap.get(key));
                resultList.add(val);
            }
        }
        return resultList;
    }

    public List<Movie> addMoive() throws IOException {
        Map<String, Map<String, Long>> tagMap = getTagMap();
        List<Movie> list = new ArrayList<>();
        // 分页
        for (int i = 1; i <= 3; i++) {
            Document doc = Jsoup.connect("http://www.sihaidy.com/list/4_" + i + ".html").get();
            Elements ul_all = doc.getElementsByAttributeValue("data-am-widget", "gallery");
            if (ul_all.size() == 0) {
                continue;
            }
            Element ul = ul_all.get(0);
            if (ul == null) {
                continue;
            }
            Elements lis = ul.getElementsByTag("li");
            int len = lis.size();
            // 处理每个电影
            for (int j = 0; j < len; j++) {
                Element li = lis.get(j);
                Element a = li.getElementsByTag("a").get(0);
                String posterUrl = a.getElementsByTag("img").get(0).attr("src");
                String movieName = a.getElementsByTag("h3").get(0).text();
                String detailHtmlUrl = URL + a.attr("href");
                // 详情页
                Document detail_doc = Jsoup.connect(detailHtmlUrl).get();
                Element div = detail_doc.getElementsByAttributeValue("class", "url").get(0);
                Element playA = div.getElementsByTag("a").get(0);
                String playDetailUrl = "http:" + playA.attr("href");
                // 播放页
                Document play_doc = Jsoup.connect(playDetailUrl).get();
                Element iframe = play_doc.getElementsByTag("iframe").first();
                if (iframe == null) {
                    continue;
                }
                String playUrl = iframe.attr("src");
                Movie m = new Movie();
                m.setName(movieName);
                m.setPlayUrl(playUrl);
                m.setPosterUrl(posterUrl);
                Elements trs = detail_doc.getElementsByTag("tr");
                if (trs != null) {//2.4.5
                    for (int k = 0; k < trs.size(); k++) {
                        if (k > 5) {
                            break;
                        }

                        // 类型
                        if (k == 2) {
                            String typeStr = "";
                            Map<String, Long> map = tagMap.get("1");
                            Element tr = trs.get(k);
                            Elements tds = tr.getElementsByTag("td");
                            // 多个类型
                            Elements as = tds.get(1).getElementsByTag("a");
                            if (as.size() > 0) {
                                for (Element e : as) {
                                    String val = e.text();
                                    if (map.containsKey(val)) {
                                        Long typeInt = map.get(val);
                                        typeStr += typeInt + ",";
                                    }
                                }

                            }
                            int strLen = typeStr.length();
                            if(strLen>0){
                                m.setType(typeStr.substring(0,typeStr.length()-1));
                            }

                        } else if (k == 4) {// 地区
                            Map<String, Long> map = tagMap.get("2");
                            Element tr = trs.get(k);
                            Elements tds = tr.getElementsByTag("td");
                            String country = tds.get(1).getElementsByTag("a").last().text();
                            if(map.containsKey(country)){
                                m.setCountry(map.get(country)+"");
                            }
                        } else if (k == 5) {
                            Element tr = trs.get(k);
                            Elements tds = tr.getElementsByTag("td");
                            String year = tds.get(1).getElementsByTag("a").last().text();
                            m.setYear(Integer.valueOf(year));
                        }
                    }
                }
                list.add(m);
            }
        }
        return list;
    }

    public void addMovieTag() throws IOException {
        Map<String, String> map = new HashMap<>();
        for (int i = 1; i <= 4; i++) {
            Document doc = Jsoup.connect("http://www.sihaidy.com/list/1_" + i + ".html").get();
            Elements ul_all = doc.getElementsByAttributeValue("data-am-widget", "gallery");
            if (ul_all.size() == 0) {
                continue;
            }
            Element ul = ul_all.get(0);
            if (ul == null) {
                continue;
            }
            Elements lis = ul.getElementsByTag("li");
            int len = lis.size();
            // 处理每个电影
            for (int j = 0; j < len; j++) {
                Element li = lis.get(j);
                Element a = li.getElementsByTag("a").get(0);
                String detailHtmlUrl = URL + a.attr("href");
                // 详情页
                Document detail_doc = Jsoup.connect(detailHtmlUrl).get();
                Element div = detail_doc.getElementsByAttributeValue("class", "url").get(0);
                Element playA = div.getElementsByTag("a").get(0);
                String playDetailUrl = "http:" + playA.attr("href");
                // 播放页
                Document play_doc = Jsoup.connect(playDetailUrl).get();
                Element iframe = play_doc.getElementsByTag("iframe").first();
                if (iframe == null) {
                    continue;
                }
                Elements trs = detail_doc.getElementsByTag("tr");
                if (trs != null) {//2.4.5
                    for (int k = 0; k < trs.size(); k++) {
                        if (k > 5) {
                            break;
                        }
                        // 类型
                        if (k == 2) {
                            Element tr = trs.get(k);
                            Elements tds = tr.getElementsByTag("td");
                            Elements as = tds.last().getElementsByTag("a");
                            if (as.size() > 0) {
                                for (Element e : as) {
                                    String val = e.text();
                                    if (!map.containsKey(val)) {
                                        MovieTag tag = new MovieTag();
                                        tag.setPid(1L);
                                        tag.setName(val);
                                        movieTagDao.insert(tag);
                                        map.put(val, tag.getId() + "");
                                    }
                                }
                            }
                        } else if (k == 4) {// 地区
                            process(map, trs.get(k), 2L);
                        } else if (k == 5) {
                            process(map, trs.get(k), 3L);
                        }
                    }

                }
            }
        }
    }


    public void process(Map<String, String> map, Element tr, Long pid) {
        Elements tds = tr.getElementsByTag("td");
        String val = tds.last().getElementsByTag("a").last().text();
        if (!map.containsKey(val)) {
            MovieTag tag = new MovieTag();
            tag.setPid(pid);
            tag.setName(val);
            movieTagDao.insert(tag);
            map.put(val, tag.getId() + "");
        }
    }

    public Map<String, Map<String, Long>> getTagMap() {
        EntityWrapper<MovieTag> ew = new EntityWrapper<>();
        ew.eq("pid", 0);
        List<MovieTag> tagList = movieTagDao.selectList(ew);
        Map<String, Map<String, Long>> map = new HashMap<>();
        for (MovieTag t : tagList) {
            EntityWrapper<MovieTag> ews = new EntityWrapper<>();
            ew.eq("pid", t.getId());
            List<MovieTag> children = movieTagDao.selectList(ews);
            Map<String, Long> childMap = new HashMap<>();
            for (MovieTag tag : children) {
                childMap.put(tag.getName(), tag.getId());
            }
            map.put(t.getId() + "", childMap);
        }
        return map;
    }

    public String getLastColumOfRow(Elements rows, int index) {
        Element tr = rows.get(index);
        return tr.getElementsByTag("td").last().getElementsByTag("a").last().text();
    }

}
